package com.luoqiz.project.mulThreadDownload;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

public class DownloaderThread extends Thread {

	private static boolean pause = false;
	private static boolean down = false;

	private DownloadInfo dlfo;
	private Properties pro;

	public DownloaderThread(DownloadInfo dlfo, Properties pro) {
		this.dlfo = dlfo;
		this.pro=pro;
	}

	@Override
	public void run() {

		try {
			
			System.out.println(dlfo.getStartPoint() + "------" + dlfo.getEndPoint());
			URL url = new URL(dlfo.getSrcPath());
			HttpURLConnection connect = (HttpURLConnection) url.openConnection();
			connect.setRequestProperty("Range", "bytes=" + dlfo.getStartPoint() + "-" + dlfo.getEndPoint());
			InputStream input = connect.getInputStream();
			RandomAccessFile raf = new RandomAccessFile(dlfo.getDestPath(), "rw");
			raf.seek(dlfo.getStartPoint()+dlfo.getAmount());

			int oldData = 0;

			byte[] b = new byte[1024];
			int len = -1;

			while ((len = input.read(b)) != -1) {
				while (isPause()) {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				raf.write(b, 0, len);
				oldData = oldData + len;
				AppMainUI.bars[dlfo.getIndex()].setValue(len + AppMainUI.bars[dlfo.getIndex()].getValue());
				AppMainUI.bars[dlfo.getIndex()].repaint();

				if (!down) {
					synchronized (this) {
						
						System.out.println("thread." + dlfo.getIndex() + ".amount");
						System.out.println("*******" + pro.getProperty("thread." + dlfo.getIndex() + ".amount"));
						oldData = oldData + Integer.parseInt(pro.getProperty("thread." + dlfo.getIndex() + ".amount"));
						pro.setProperty("thread." + dlfo.getIndex() + ".amount", oldData + "");
						File destFile = new File(dlfo.getDestPath());
						File f = new File(destFile.getParentFile(),
								destFile.getName().substring(0, destFile.getName().lastIndexOf(".")) + ".yundowns");
						
						pro.store(new FileOutputStream(f), null);
						System.out.println("new Data:"+oldData);
					}
					break;
				}
			}

			input.close();
			raf.close();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	public static boolean isPause() {
		return pause;
	}

	public static void setPause(boolean pause) {
		DownloaderThread.pause = pause;
	}

	public static boolean isDown() {
		return down;
	}

	public static void setDown(boolean down) {
		DownloaderThread.down = down;
	}
}
